// 生产token的jwt
const jwt = require('jsonwebtoken')

// 引入处理时间的moment
const moment = require('moment')

// 引入 orders 表
const orders = require('../../models/orders')
// 引入 goods 表
const goods = require('../../models/goods')
// 引入 users 表
const users = require('../../models/users')

// 分页查询
list = (req,res)=>{
    // console.log(req.query)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            // token验证成功之后
            let order = {}
            req.query.orderCode ? order.orderCode = req.query.orderCode : ''
            // 时间格式转换
            // console.log(moment(req.query.buyTime).format())
            req.query.buyTime ? order.buyTime = {'$gt':moment(req.query.buyTime).format()} : ''
            orders.find(
                // 订单编号不用模糊查询
                order
                // 分页查询,populate查询关联的表
            ).skip((req.query.currentPage - 1) * req.query.pageSize).limit(Number(req.query.pageSize)).populate('userID').populate('goodsID')
            .then(result=>{
                // 这里返回的是存储的格陵兰时间，得转换一下
                // result数组对象添加新属性加不了，所以就拷贝了一个新的，这样就没问题了
                let temp = JSON.parse(JSON.stringify(result))
                for(let item of temp){
                    item.buyTimeFormat = moment(item.buyTime).format('YYYY-MM-DD HH:mm:ss')
                    // console.log(moment(item.buyTime).format('YYYY-MM-DD HH:mm:ss'))
                }
                // 这里的查询是为了查总条数
                orders.find(
                    order
                ).countDocuments()
                .then(result2=>{
                    res.json({code:200,data:temp,total:result2})
                })
            })
            // 这里就不通过商品名字筛选了，因为在另外一张表，用populate的match如果没有，那就是null，事后还得自己去删除组合数据，很麻烦
            // orders.find().populate({path:'userID',match:{username:'铨'}}).populate({path:'goodsID',match:{goodsname:{$regex: '1',$options:'i'}}}).then(result=>{
            //     res.json({code:200,data:result})
            // })
        }
    });
}
// 删除
deleteOrder = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            orders.findByIdAndDelete({_id:req.params.id}).then(result=>{
                res.json({code:200,data:result})
            })
        }
    });
}

// 新增
addOrder = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let _order = {}
            goods.findOne({_id:req.body.goodsID}).then(result1=>{
                users.findOne({_id:req.body.userID}).then(result2=>{
                    // console.log(result1)
                    // console.log(result2)
                    
                    if(result1 && result2){
                        _order.userID = req.body.userID
                        _order.goodsID = req.body.goodsID
                        _order.buyNum = req.body.buyNum
                        _order.buyTime = new Date()
                        _order.orderCode = '1998718-' + Date.now()
                        _order.buyPrice = result1.price

                        // console.log(_order)
                        new orders(_order).save().then(result=>{
                            // console.log(result)
                            res.json({code:200,data:result})
                        })
                    }else{
                        res.json({code:599,msg:'数据库没有该用户或该商品！'})
                    }

                }).catch(error2=>{
                    console.log(error2)
                    res.json({code:599,msg:'添加出问题了！请重试！'})
                })
            }).catch(error1=>{
                console.log(error1)
                res.json({code:599,msg:'添加出问题了！请重试！'})
            })
        }
    });
}
// 修改
updateOrder = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let _order = {}
            goods.findOne({_id:req.body.goodsID}).then(result1=>{
                users.findOne({_id:req.body.userID}).then(result2=>{
                    // console.log(result1)
                    // console.log(result2)
                    
                    if(result1 && result2){
                        _order.userID = req.body.userID
                        _order.goodsID = req.body.goodsID
                        _order.buyNum = req.body.buyNum
                        _order.buyTime = new Date()

                        // console.log(_order)
                        orders.updateOne({_id:req.params.id},{$set:_order}).then(result=>{
                            // 这里返回的是修改之前的值
                            res.json({code:200,data:result})
                        })
                    }else{
                        res.json({code:599,msg:'数据库没有该用户或该商品！'})
                    }

                }).catch(error2=>{res.json({code:599,msg:'添加出问题了！请重试！'})})
            }).catch(error1=>{res.json({code:599,msg:'添加出问题了！请重试！'})})
        }
    });
}

// 购买商品
buyGoods = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let _order = {}
            goods.findOne({_id:req.body.goodsID}).then(result1=>{
                users.findOne({_id:req.body.userID}).then(result2=>{
                    // console.log(result1)
                    // console.log(result2)
                    // 没得商品或者用户
                    if(result1 && result2){
                        if(result2.money <= req.body.totalPrice){
                            res.json({code:599,msg:'余额不够,请充值!'})
                           
                        }else if(!result2.address){
                            res.json({code:599,msg:'请先填写收货地址!'})                   
                        }else{
                            _order.userID = req.body.userID
                            _order.goodsID = req.body.goodsID
                            _order.buyNum = req.body.buyNum
                            _order.buyTime = new Date()
                            _order.orderCode = '1998718-' + Date.now()
                            _order.buyPrice = result1.price

                            // console.log(_order)
                            new orders(_order).save().then(result=>{
                                // console.log(result)
                                res.json({code:200,data:result})
                            })
                        }
                    }else{
                        res.json({code:599,msg:'数据库没有该用户或该商品！'})
                    }

                }).catch(error2=>{
                    console.log(error2)
                    res.json({code:599,msg:'添加出问题了！请重试！'})
                })
            }).catch(error1=>{
                console.log(error1)
                res.json({code:599,msg:'添加出问题了！请重试！'})
            })
        }
    });
}

module.exports = {
    list,deleteOrder,addOrder,updateOrder,buyGoods
}